package com.liuhangs.learning.crowd.webui.security.service.impl;

import com.liuhangs.learning.crowd.webui.bean.auth.Role;
import com.liuhangs.learning.crowd.webui.bean.auth.User;
import com.liuhangs.learning.crowd.webui.mapper.AdminUserMapper;
import com.liuhangs.learning.crowd.webui.security.service.PermissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import static java.util.stream.Collectors.toSet;

/**校验登陆用户是否有权限访问此接口
 * @author 11757
 * @DATE 2020/6/18
 */
@Service("permissionService")
public class PermissionServiceImpl implements PermissionService {

    private static final Logger logger = LoggerFactory.getLogger(PermissionServiceImpl.class);

    @Autowired
    private AdminUserMapper adminUserMapper;

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication)
    {
        Object principal = authentication.getPrincipal();
        if (null != principal && principal instanceof UserDetails)
        {
            //获取登陆的账号
            UserDetails userDetails = (UserDetails) principal;
            String account = userDetails.getUsername();

            //根据账号查询用户信息
            User user = adminUserMapper.queryUserInfoByAcc(account);
            if (user == null || CollectionUtils.isEmpty(user.getRoles()))
            {
                return false;
            }
            //解析用户信息中包含的所有权限
            List<Role> roles = user.getRoles();
            Set<String> urls = roles.stream().map(t -> t.getPermissions()).flatMap
                    (Collection::stream).map(t -> t.getUrl()).collect(toSet());

            logger.info("用户权限为:{}",urls);
            //判断用户是否能访问当前资源
            return urls.stream().anyMatch(t -> new AntPathMatcher().match(t, request
                    .getRequestURI()));

        }
        return false;
    }
}
